package com.my.micro.service.good.ribbon;

import cn.hutool.http.HttpUtil;
import com.google.common.collect.Lists;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.LoadBalancerBuilder;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.reactive.LoadBalancerCommand;
import rx.Observable;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 测试单独使用ribbon
 *
 * @author Zijian Liao
 * @since 1.0.0
 */
public class RibbonDemo {


    public static void main(String[] args) {
        String api = "/order/get";
        List<Server> servers = Lists.newArrayList(new Server("127.0.0.1", 8081),
                new Server("127.0.0.1", 8082));
        LoadBalancerBuilder<Server> serverLoadBalancerBuilder = LoadBalancerBuilder.newBuilder();
        ILoadBalancer loadBalancer = serverLoadBalancerBuilder.buildFixedServerListLoadBalancer(servers);
        LoadBalancerCommand<String> command = LoadBalancerCommand.<String>builder()
                .withLoadBalancer(loadBalancer)
                .build();
        for (int i = 0; i < 5; i++) {
            String result = command.submit(server -> {
                String pattern = "http://%s:%s";
                String url = String.format(pattern, server.getHost(), server.getPort()) + api;
                System.out.println("调用地址：" + url);
                return Observable.just(HttpUtil.get(url));
            }).toBlocking().first();
            System.out.println(result);
        }
    }

}
